<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card class="box-card">
            <div slot="header">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-input placeholder="请输入内容" clearable @clear="getUserList" v-model="queryInfo.query">
                            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                        </el-input>
                    </el-col>
                    <el-col :span="4">
                        <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
                    </el-col>
                </el-row>
            </div>
           <el-table :data="userList" border stripe>
               <el-table-column type="index" label="序号" width="70px"></el-table-column>
               <el-table-column label="姓名" prop="username"></el-table-column>
               <el-table-column label="邮箱" prop="email"></el-table-column>
               <el-table-column label="电话" prop="mobile"></el-table-column>
               <el-table-column label="角色" prop="role_name"></el-table-column>
               <el-table-column label="状态">
                   <template slot-scope="scope">
                       <el-switch v-model="scope.row.me_state" @change="userState(scope.row)"></el-switch>
                   </template>
               </el-table-column>
               <el-table-column label="操作">
                   <template slot-scope="scope">
                       <el-button type="primary" icon="el-icon-edit" @click="editDialog(scope.row.id)"></el-button>
                       <el-button type="danger" icon="el-icon-delete" @click="deleteUserById(scope.row.id)"></el-button>
                       <el-tooltip effect="dark" content="分配角色" placement="top">
                           <el-button type="warning" icon="el-icon-setting" @click="addRights(scope.row)"></el-button>
                       </el-tooltip>
                   </template>
               </el-table-column>
           </el-table>

            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[1, 2, 3, 4]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <el-dialog
                title="分配角色"
                :visible.sync="dialogRights"
                width="50%"
        >
            <div>
                <p>用户名: {{userInfo.username}}</p>
                <p>手机号: {{userInfo.mobile}}</p>
                <p>分配角色:
                    <el-select v-model="selectId" placeholder="请选择">
                        <el-option
                                v-for="item in userRightsList"
                                :key="item.id"
                                :label="item.roleName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </p>

            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogRights = false">取 消</el-button>
                <el-button type="primary" @click="saveRolesInfo">确 定</el-button>
            </span>
        </el-dialog>



        <el-dialog
                title="添加用户"
                :visible.sync="dialogVisible"
                width="50%"
                @close="closeDialog"
        >
            <el-form :model="addUser" ref="userRef" :rules="addUserRules">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUser.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUser.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUser.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addUser.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUsers">确 定</el-button>
            </span>
        </el-dialog>


        <el-dialog
                title="修改用户"
                :visible.sync="dialogVisibleEdit"
                width="50%"
                @close="editDialogs"
        >
            <el-form :model="editUser" :rules="editUserRules" ref="editUserRef">
                <el-form-item label="用户名">
                    <el-input v-model="editUser.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUser.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editUser.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleEdit = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { getUsers,updateState,addUserss,getUser,editUser,deleteUsers,getRoles,putUserRoles } from "../api/user";

    export default {
        name: "Users",
        data() {
            return {
                selectId: '',
                userRightsList: [],
                userInfo: {},
                dialogRights: false,
                editUser: {},
                dialogVisibleEdit: false,
                queryInfo: {
                    query: '',
                    pagenum: 1,
                    pagesize: 2
                },
                userList: [],
                total: 0,
                dialogVisible: false,
                addUser: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''
                },
                addUserRules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
                    password: [{ required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
                    email: [{ required: true, message: '请输入邮箱', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
                    mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }]
                },
                editUserRules: {
                    email: [{ required: true, message: '请输入邮箱', trigger: 'blur' },
                        { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'} ],
                    mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },
                        { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }]
                }

            }
        },
        created() {
            this.getUserList()
        },
        methods: {
            // 点击按钮，分配角色
            async saveRolesInfo() {
                if (!this.selectId) {
                    return this.$message.error('请选择要分配的角色')
                }else {
                    const res = await putUserRoles(this.userInfo.id,this.selectId)
                    console.log(res)
                }
            },
            // 分配角色权限
            async addRights(row) {
                this.userInfo = row
                const res = await getRoles()
                this.userRightsList = res.data.data
                console.log(res)

                this.dialogRights = true
            },
            // 删除 用户
            async deleteUserById(id) {
                const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                        this.$message({
                            type: 'success',
                            message: '删除用户成功!'
                        })
                }).catch(error => error)
                console.log(confirmResult)
                if (confirmResult !== 'cancel') {
                    deleteUsers(id).then(res => {
                        this.getUserList()
                    })
                }else {
                    return this.$message.info('已取消删除')
                }

            },
            // 修改表单，并提交信息
            editUserInfo() {
              this.$refs.editUserRef.validate(valid => {
                  if (valid) {
                      editUser(this.editUser.id,{email:this.editUser.email,mobile: this.editUser.mobile}).then(res => {
                      if (res.data.meta.status === 200) {
                          this.dialogVisibleEdit = false
                          this.getUserList()
                          this.$message.success({
                              type: 'success',
                              message: '修改用户信息成功'
                          })

                      }
                      })

                  } else {
                      this.$message.error('修改用户信息失败')
                  }
              })
            },
            // 重置修改弹框验证
            editDialogs() {
              this.$refs.editUserRef.resetFields()
            },
            // 修改用户
            editDialog(id) {
                this.dialogVisibleEdit = true
                getUser(id).then(res => {
                    this.editUser = res.data.data
                })
            },
            // 添加用户
            addUsers() {
                this.$refs.userRef.validate(valid => {
                    if (valid) {
                        addUserss(this.addUser).then(res => {
                            if (res.data.meta.status === 201) {
                                this.$message.success({
                                    type: 'success',
                                    message: '成功添加用户'
                                })
                                this.dialogVisible = false
                            } else {
                                this.$message.error('添加失败')
                            }
                        })
                    } else {
                        return
                    }
                })
            },
            //Dialog关闭时，重置表单
            closeDialog() {
                this.$refs.userRef.resetFields()
            },
            userState(userInfo) {
                updateState(userInfo.id,userInfo.mg_state).then(res => {
                    if (res.data.meta.status === 200) {
                        this.$message.success({
                            type: 'success',
                            message: '状态设置成功'
                        })
                    } else {
                        userInfo.mg_state = !userInfo.mg_state
                        this.$message.error('状态设置失败')
                    }
                })

            },
            handleSizeChange(newSize) {
                this.queryInfo.pagesize = newSize
                this.getUserList()
            },
            handleCurrentChange(newPage) {
                this.queryInfo.pagenum = newPage
                this.getUserList()
            },
           async getUserList() {
                const res = await getUsers(this.queryInfo)
               if (res.data.meta.status !== 200) {
                   this.$message.error('获取用户列表失败')
               } else {
                   this.userList = res.data.data.users
                   this.total = res.data.data.total
               }
           }
        }
    }
</script>

<style scoped>
    .el-breadcrumb {
        margin-bottom: 15px;
        font-size: 15px;
    }

    .el-table {
        margin-top: 15px;
        font-size: 17px;
    }

</style>
